import { defineStore } from "pinia";
import { useAccountStore } from "./account";
import { wsManager } from "../utils/wsManager";
import { nextTick } from "vue";

export const useStartLoadingStore = defineStore("startLoading", {
	state: () => {
		return {
			isInitializing: false,
			isInitialized: false,
			initProgress: 0,
			initStatus: "系统启动中",
			showStartLoading: true,
		};
	},
	getters: {
		canShowApp: (state) => {
			return state.isInitialized && !state.showStartLoading;
		},
	},
	actions: {
		sleep(ms) {
			return new Promise((resolve) => setTimeout(resolve, ms));
		},
		// 系统初始化方法（从 index.ts 抽离出来）
		async initializeSystem() {
			if (this.isInitializing || this.isInitialized) {
				return;
			}
			this.isInitializing = true;
			this.initProgress = 5;
			await this.sleep(50);
			this.initStatus = "系统启动中";
			try {
				await nextTick();

				// 模拟初始化进度
				this.updateProgress(30, "检查登录状态");
				await this.sleep(50);
				// 检查用户登录状态（通过 token 判断）
				if (!useAccountStore().isLogin) {
					// console.log("❌ [SunAdmin] 用户未登录，跳过业务初始化");
					this.updateProgress(100, "启动完成");
					this.completeInitialization();
					return;
				}

				this.updateProgress(50, "验证用户信息");
				await this.sleep(100);
				// 更新用户信息（同时验证 token）
				let res = await useAccountStore().tokenAuth();

				if (res.code == 200) {
					this.updateProgress(80, "建立连接");

					// 建立 WebSocket 连接
					wsManager.connect();
					// console.log("✅ [SunAdmin] Token 验证成功，用户信息已更新");

					this.updateProgress(100, "启动成功");
				} else {
					// console.log("❌ Token 验证失败, 未登录");
					this.updateProgress(100, "启动完成");
				}
				this.completeInitialization();
			} catch (error) {
				console.error("❌ [SunAdmin] 系统初始化失败:", error);
				this.updateProgress(100, "启动完成");
				this.completeInitialization();
			}
		},

		// 更新初始化进度
		updateProgress(progress, status) {
			this.initProgress = progress;
			this.initStatus = status;
		},

		// 完成初始化
		completeInitialization() {
			this.isInitializing = false;
			this.isInitialized = true;

			// 延迟隐藏启动画面
			setTimeout(() => {
				this.showStartLoading = false;
			}, 500);
		},

		// 重置系统状态（用于重新初始化）
		resetSystem() {
			this.isInitializing = false;
			this.isInitialized = false;
			this.initProgress = 0;
			this.initStatus = "系统启动中";
			this.showStartLoading = true;
		},
	},
});
